package cn.xscrum.vtsp.controller;

import cn.xscrum.common.annotation.Log;
import cn.xscrum.common.core.controller.BaseController;
import cn.xscrum.common.core.domain.AjaxResult;
import cn.xscrum.common.core.page.TableDataInfo;
import cn.xscrum.common.enums.BusinessType;
import cn.xscrum.common.utils.poi.ExcelUtil;
import cn.xscrum.vtsp.domain.VtspActivity;
import cn.xscrum.vtsp.domain.VtspAdviserManage;
import cn.xscrum.vtsp.domain.VtspAreas;
import cn.xscrum.vtsp.domain.VtspDuties;
import cn.xscrum.vtsp.service.IVtspActivityService;
import cn.xscrum.vtsp.service.IVtspAdviserManageService;
import cn.xscrum.vtsp.service.IVtspAreasService;
import cn.xscrum.vtsp.service.IVtspDutiesService;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 志愿者顾问管理Controller
 *
 * @author liuwl
 * @date 2021-10-01
 */
@Controller
@RequestMapping("/vtsp/advisermanage")
public class VtspAdviserManageController extends BaseController
{
    //template资源前缀
    private String prefix = "vtsp/advisermanage";

    @Autowired
    private IVtspAdviserManageService vtspAdviserManageService; //定义志愿者顾问Service接口对象

    @Autowired
    private IVtspAreasService vtspAreasService; //定义国家地区管理Service接口对象
    @Autowired
    private IVtspDutiesService vtspDutiesService;   //定义职务Service接口对象
    @Autowired
    private IVtspActivityService vtspActivityService;   //定义活动Service接口对象



    /**
     * 初始加载的志愿者顾问信息
     *
     * @return 志愿者顾问管理页面
     */
    @RequiresPermissions("team:advisermanage:view")
    @GetMapping()
    public String adviser()
    {
        return prefix + "/advisermanage";
    }

    /**
     * 查询志愿者顾问列表
     *
     * @param vtspAdviserManage 志愿者顾问信息
     * @return 查询到的志愿者顾问信息列表
     */
    @RequiresPermissions("team:advisermanage:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(VtspAdviserManage vtspAdviserManage)
    {
        //获取志愿者顾问列表信息
        List<VtspAdviserManage> list = vtspAdviserManageService.selectVtspAdviserManageList(vtspAdviserManage);
        //数据回显
        for(VtspAdviserManage adviserManage : list)
        {
            if(adviserManage != null)
            {
                String duties = adviserManage.getAdviserJob();
                //利用正则表达式判断duties是否为数字
                Pattern pattern = Pattern.compile("[0-9]+");
                Matcher isNum = pattern.matcher(duties);
                if(isNum.matches())        //为数字
                {
                    Long dutiesId = Long.parseLong(duties);         //String转Long
                    VtspDuties vtspDuties = vtspDutiesService.selectVtspDutiesById(dutiesId);
                    String dutiesName = vtspDuties.getDutiesName();
                    adviserManage.setAdviserJob(dutiesName);        //回显
                }
            }
        }
        startPage();
        return getDataTable(list);
    }

    /**
     * 导入下载模板
     *
     * @return 模版
     */
    @RequiresPermissions("team:advisermanage:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        //创建Excel工具类
        ExcelUtil<VtspAdviserManage> util = new ExcelUtil<VtspAdviserManage>(VtspAdviserManage.class);
        return util.importTemplateExcel("志愿者顾问信息");
    }

    /**
     * 导入志愿者顾问管理列表
     *
     * @param file 获取文件对象
     * @return 导入成功结果
     */
    @RequiresPermissions("team:advisermanage:import")
    @Log(title = "志愿者顾问管理", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    @ResponseBody
    public AjaxResult importList(MultipartFile file) throws Exception
    {
        //创建Excel工具类
        ExcelUtil<VtspAdviserManage> util = new ExcelUtil<VtspAdviserManage>(VtspAdviserManage.class);
        //选择导入文件
        List<VtspAdviserManage> list = util.importExcel(file.getInputStream());
        //导入文件
        String message = vtspAdviserManageService.importList(list);
        return AjaxResult.success(message);
    }

    /**
     * 导出志愿者顾问管理列表
     *
     * @param vtspAdviserManage 志愿者顾问信息
     */
    @RequiresPermissions("team:advisermanage:export")
    @Log(title = "志愿者顾问管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult exportList(VtspAdviserManage vtspAdviserManage)
    {
        //获取志愿者顾问信息
        List<VtspAdviserManage> list = vtspAdviserManageService.selectVtspAdviserManageList(vtspAdviserManage);
        //创建Excel表格并导出
        ExcelUtil<VtspAdviserManage> util = new ExcelUtil<VtspAdviserManage>(VtspAdviserManage.class);
        return util.exportExcel(list, "adviserManage");
    }

    /**
     * 新增志愿者顾问管理
     *
     * @return 志愿者顾问管理新增页面
     */
    @GetMapping("/add")
    public String add(Model model)
    {
        //获取vtsp_areas的数据
        List<VtspAreas> areasList = vtspAreasService.selectVtspAreasList(new VtspAreas());
        //获取职务列表
        List<VtspDuties> dutiesList = vtspDutiesService.selectVtspDutiesList(new VtspDuties());
        //获取vtsp_areas的国家信息，即parent_id = 0；若parent_id != 0，则为城市信息
        List<VtspAreas> countryList = new ArrayList<VtspAreas>();        //国家
        List<VtspAreas> cityList = new ArrayList<VtspAreas>();           //省市
        for(VtspAreas vtspAreas : areasList)
        {
            if(vtspAreas != null)
            {
                if(vtspAreas.getParentId() == 0)    //国家
                {
                    countryList.add(vtspAreas);
                }
                else
                {
                    cityList.add(vtspAreas);
                }
            }
        }
        model.addAttribute("countryList", countryList);
        model.addAttribute("cityList", JSON.toJSONString(cityList));
        model.addAttribute("dutiesList", dutiesList);
        return prefix + "/add";
    }

    /**
     * 新增保存志愿者顾问管理
     *
     * @param vtspAdviserManage 志愿者顾问信息
     * @return 新增结果
     */
    @RequiresPermissions("team:advisermanage:add")
    @Log(title = "志愿者顾问管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(VtspAdviserManage vtspAdviserManage)
    {
        return toAjax(vtspAdviserManageService.insertVtspAdviserManage(vtspAdviserManage));
    }

    /**
     * 修改志愿者顾问管理
     *
     * @param adviserId 志愿者顾问信息ID
     * @param mmap ModelMap对象
     * @return 修改页面的数据
     */
    @GetMapping("/edit/{adviserId}")
    public String edit(@PathVariable("adviserId") Long adviserId, ModelMap mmap)
    {
        //获取vtsp_areas的数据
        List<VtspAreas> areasList = vtspAreasService.selectVtspAreasList(new VtspAreas());
        //获取职务列表
        List<VtspDuties> dutiesList = vtspDutiesService.selectVtspDutiesList(new VtspDuties());
        //获取vtsp_areas的国家信息，即parent_id = 0；若parent_id != 0，则为城市信息
        List<VtspAreas> countryList = new ArrayList<VtspAreas>();        //国家
        List<VtspAreas> cityList = new ArrayList<VtspAreas>();           //省市
        for(VtspAreas vtspAreas : areasList)
        {
            if(vtspAreas != null)
            {
                if(vtspAreas.getParentId() == 0)    //国家
                {
                    countryList.add(vtspAreas);
                }
                else
                {
                    cityList.add(vtspAreas);
                }
            }
        }
        //根据adviserId查询需要修改的志愿者顾问信息
        VtspAdviserManage vtspAdviserManage = vtspAdviserManageService.selectVtspAdviserManageById(adviserId);
        //获取adviserId的volunteer_areaid，由此获取vtsp_areas信息
        Long areasId = vtspAdviserManage.getVolunteerAreaid();
        VtspAreas vtspAreas = vtspAreasService.selectVtspAreasById(areasId);
        //展示修改页面的数据
        mmap.put("vtspAdviserManage", vtspAdviserManage);
        mmap.put("countryList", countryList);
        mmap.put("cityList", JSON.toJSONString(cityList));
        mmap.put("vtspAreas",JSON.toJSONString(vtspAreas));
        mmap.put("dutiesList", dutiesList);
        return prefix + "/edit";
    }

    /**
     * 修改保存志愿者顾问管理
     *
     * @param vtspAdviserManage 志愿者顾问信息
     * @return 修改结果
     */
    @RequiresPermissions("team:advisermanage:edit")
    @Log(title = "志愿者顾问管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(VtspAdviserManage vtspAdviserManage)
    {
        return toAjax(vtspAdviserManageService.updateVtspAdviserManage(vtspAdviserManage));
    }

    /**
     * 删除志愿者顾问信息
     *
     * @param ids 需要删除的数据ID
     * @return 删除结果
     */
    @RequiresPermissions("team:advisermanage:remove")
    @Log(title = "志愿者顾问管理", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        vtspAdviserManageService.deleteVtspActivityAdviserByIds(ids);   //先删除外键表数据
        return toAjax(vtspAdviserManageService.deleteVtspAdviserManageByIds(ids));
    }

    /**
     * 查看志愿者顾问详情
     *
     * @param adviserId 志愿者顾问信息ID
     * @param mmap ModelMap对象
     * @return 志愿者顾问详情列表
     */
    @GetMapping("/detail/{adviserId}")
    public String detail(@PathVariable("adviserId") Long adviserId, ModelMap mmap)
    {
        //根据adviserId查询志愿者顾问信息
        VtspAdviserManage vtspAdviserManage = vtspAdviserManageService.selectVtspAdviserManageById(adviserId);
        if(vtspAdviserManage != null)
        {
            String duties = vtspAdviserManage.getAdviserJob();
            //利用正则表达式判断duties是否为数字
            Pattern pattern = Pattern.compile("[0-9]+");
            Matcher isNum = pattern.matcher(duties);
            if(isNum.matches())        //为数字
            {
                Long dutiesId = Long.parseLong(duties);         //String转Long
                VtspDuties vtspDuties = vtspDutiesService.selectVtspDutiesById(dutiesId);
                String dutiesName = vtspDuties.getDutiesName();
                vtspAdviserManage.setAdviserJob(dutiesName);        //回显
            }
        }
        //展示详情页面的数据
        mmap.put("vtspAdviserManage", vtspAdviserManage);
        return prefix + "/detail";
    }

    /**
     * 查询志愿者顾问参与的活动详情
     *
     * @param adviserId 志愿者顾问信息ID
     * @param mmap ModelMap对象
     * @return 查询到的志愿者顾问参与的活动
     */
    @PostMapping("/detail/{adviserId}")
    @ResponseBody
    public TableDataInfo listA(@PathVariable("adviserId") Long adviserId, ModelMap mmap)
    {
        mmap.put("adviserId" ,adviserId);
        //获取志愿者顾问参与的活动
        List<VtspAdviserManage> list = vtspAdviserManageService.selectVtspActivityList(adviserId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  //日期格式化
        List<VtspActivity> activityList = new ArrayList<VtspActivity>();        //参与的活动
        if(list.size() > 0 )
        {
            for(VtspAdviserManage vtspAdviserManage : list)
            {
                if(vtspAdviserManage != null)
                {
                    List<VtspActivity> activity = vtspAdviserManage.getActivities();    //单个活动
                    if(activity.size() > 0)
                    {
                        //设置活动时间为：活动开始时间 至 活动结束时间
                        String activityTime = sdf.format(activity.get(0).getActivityBegin()) + " 至 " + sdf.format(activity.get(0).getActivityEnd());
                        activity.get(0).setActivityTime(activityTime);
                        //参与的活动列表
                        activityList.add(activity.get(0));
                    }
                }
            }
        }
        startPage();
        return getDataTable(activityList);
    }
}
